package com.linlang.grasharepro.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.linlang.grasharepro.R;
import com.linlang.grasharepro.adapter.MyShareAdapter;
import com.linlang.grasharepro.dao.FollowDB;
import com.linlang.grasharepro.dao.MyShareDB;
import com.linlang.grasharepro.dao.ShareCoentenDB;
import com.linlang.grasharepro.dao.UserDB;
import com.linlang.grasharepro.model.MessageItem;
import com.linlang.grasharepro.model.ShareCoenten;
import com.linlang.grasharepro.utils.ListViewUitls;
import com.linlang.grasharepro.view.ListViewCompat;
import com.linlang.grasharepro.view.SlideView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lixin on 2016-8-8.
 */
public class MyShareActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener,
        SlideView.OnSlideListener, ListViewCompat.OnRefreshListener, ListViewCompat.OnLoadListener{

    private ListViewCompat mListView;
    private List<MessageItem> mMessageItems = new ArrayList<MessageItem>();
    private SlideView mLastSlideViewWithStatusOn;
    private SlideAdapter adapter;
    private int allCount = 40;


    private ArrayList<ShareCoenten> collect_list = new ArrayList<ShareCoenten>();
    private ShareCoentenDB shareCoentenDB;
    private ShareCoentenDB myShareDB;
    private ShareCoenten info = null;
    String account = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mysharecontent);
        // 获取从列表当中传递过来的数据
        Intent intent = getIntent();
        Bundle bund = intent.getExtras();
        if (bund != null && bund.getSerializable("shareContent") != null)
            info = (ShareCoenten) bund.getSerializable("shareContent");

        initView();
        loadData(ListViewCompat.REFRESH);
    }

    public void initView() {
        mListView = (ListViewCompat) findViewById(R.id.lv_myshare);
        adapter = new SlideAdapter();
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        mListView.setOnRefreshListener(this);
        mListView.setOnLoadListener(this);

    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(700);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = handler.obtainMessage();
                msg.what = what;
                msg.obj = getMyShares();
                handler.sendMessage(msg);
            }
        }).start();
    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            List<MessageItem> result = (List<MessageItem>) msg.obj;
            switch (msg.what) {
                case ListViewCompat.REFRESH:
                    mListView.onRefreshComplete();
                    mMessageItems.clear();
                    mMessageItems.addAll(result);
                    break;
                case ListViewCompat.LOAD:
                    mListView.onLoadComplete();
                    mMessageItems.addAll(result);
                    break;
                case 2:
//                    mListView.onLoadComplete();
//                    Toast.makeText(MyCollectActivity.this, "已加载全部！", Toast.LENGTH_SHORT).show();
                    break;
            }
            mListView.setResultSize(result.size());
            adapter.notifyDataSetChanged();
        }

        ;
    };

    private class SlideAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        SlideAdapter() {
            super();
            mInflater = getLayoutInflater();
        }

        @Override
        public int getCount() {
            return mMessageItems.size();
        }

        @Override
        public Object getItem(int position) {
            return mMessageItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            SlideView slideView = (SlideView) convertView;
            if (slideView == null) {
                View itemView = mInflater.inflate(R.layout.item_listview_delete, null);

                slideView = new SlideView(MyShareActivity.this);
                slideView.setContentView(itemView);

                holder = new ViewHolder(slideView);
                slideView.setOnSlideListener(MyShareActivity.this);
                slideView.setTag(holder);
            } else {
                holder = (ViewHolder) slideView.getTag();
            }
            final MessageItem item = mMessageItems.get(position);
            item.slideView = slideView;
            item.slideView.shrink();
//            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),item.iconRes);
//            Bitmap rebitmap = new Utils().toRoundBitmap(bitmap);
            holder.icon.setImageResource(item.iconRes);
            holder.title.setText(item.title);
            holder.msg.setText(item.msg);
            holder.time.setText(item.time);
            holder.deleteHolder.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mMessageItems.remove(position);
                    adapter.notifyDataSetChanged();

                    //删除我的收藏数据表
                    //获取用户登陆信息
                    SharedPreferences preferences = getSharedPreferences("userInfo",
                            Activity.MODE_PRIVATE);
                    String account = preferences.getString("account", "");

                    myShareDB = new ShareCoentenDB(MyShareActivity.this);
                    myShareDB.open();
                    myShareDB.deleteById(item.id);
                }
            });
            holder.edit.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    adapter.notifyDataSetChanged();
                    Toast.makeText(MyShareActivity.this, "编辑" + position + "个条", Toast.LENGTH_LONG).show();
                }
            });

            return slideView;
        }

    }


    private static class ViewHolder {
        public ImageView icon;
        public TextView title;
        public TextView msg;
        public TextView time;
        public TextView deleteHolder;
        public TextView edit;

        ViewHolder(View view) {
            icon = (ImageView) view.findViewById(R.id.icon);
            title = (TextView) view.findViewById(R.id.title);
            msg = (TextView) view.findViewById(R.id.msg);
            time = (TextView) view.findViewById(R.id.time);
            deleteHolder = (TextView) view.findViewById(R.id.delete);
            edit = (TextView) view.findViewById(R.id.edit);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {

    }

    @Override
    public void onSlide(View view, int status) {
        if (mLastSlideViewWithStatusOn != null && mLastSlideViewWithStatusOn != view) {
            mLastSlideViewWithStatusOn.shrink();
        }

        if (status == SLIDE_STATUS_ON) {
            mLastSlideViewWithStatusOn = (SlideView) view;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.holder:

                break;

            default:
                break;
        }
    }

    @Override
    public void onLoad() {
        // TODO Auto-generated method stub
        if (adapter.getCount() < allCount) {
            loadData(ListViewCompat.LOAD);
        } else {
            Message msg = handler.obtainMessage();
            msg.what = 2;
            msg.obj = mMessageItems;
            handler.sendMessage(msg);

        }
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        loadData(ListViewCompat.REFRESH);
    }

    private List<MessageItem> getMyShares() {

        List<MessageItem> result = new ArrayList<MessageItem>();

        //获取用户登陆信息
        SharedPreferences preferences = getSharedPreferences("userInfo",
                Activity.MODE_PRIVATE);

        if (info != null && (info.getUserName() != null || info.getUserName() != "")) {
            account = info.getUserName();
        } else {
            account = preferences.getString("account", "");
        }

        shareCoentenDB = new ShareCoentenDB(this);
        shareCoentenDB.open();

        collect_list = shareCoentenDB.queryByWhere(account);

        for (int i = 0; i < collect_list.size(); i++) {
            MessageItem item = new MessageItem();
            item.id = collect_list.get(i).get_id();
            item.msg = collect_list.get(i).getContent();
            item.title = collect_list.get(i).getTitle();
            item.time = collect_list.get(i).getTime();
            result.add(item);
        }
        return result;
    }








//    private void initView() {
//        //获取用户登陆信息
//        SharedPreferences preferences = getSharedPreferences("userInfo",
//                Activity.MODE_PRIVATE);
//
//        if (info != null && (info.getUserName() != null || info.getUserName() != "")) {
//            account = info.getUserName();
//        } else {
//            account = preferences.getString("account", "");
//        }
//
//        shareCoentenDB = new ShareCoentenDB(this);
//        shareCoentenDB.open();
//
//        collect_list = shareCoentenDB.queryByWhere(account);
//
//
//        lv_myshare = (ListView) findViewById(R.id.lv_myshare);
//        final MyShareAdapter myShareAdapter = new MyShareAdapter(collect_list, this);
//        lv_myshare.setAdapter(myShareAdapter);
//        ListViewUitls.setListViewHeightBasedOnChildren(lv_myshare);
//
//        lv_myshare.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//                iv_delete = (ImageView) view.findViewById(R.id.iv_delete);
//                iv_delete.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        myShareDB = new MyShareDB(MyShareActivity.this);
//                        myShareDB.open();
//                        boolean isDelete = myShareDB.deleteByRelationId(collect_list.get(position).get_id(), account);
//
//                        if (isDelete) {
//                            shareCoentenDB = new ShareCoentenDB(MyShareActivity.this);
//                            shareCoentenDB.open();
//                            collect_list.addAll(shareCoentenDB.queryMyShare(account));
//                            myShareAdapter.setList(collect_list);
//                            myShareAdapter.notifyDataSetChanged();
//                        } else {
//                            Toast.makeText(MyShareActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
//            }
//        });
//    }
}
